/*
 * @Author: shengduiliang 1107722390@qq.com
 * @Date: 2024-05-06 21:28:01
 * @LastEditors: shengduiliang 1107722390@qq.com
 * @LastEditTime: 2024-05-06 22:04:49
 * @FilePath: /treasure/src/pages/treasury/index/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE 
 */
import { View } from '@tarojs/components'
import { Tabbar } from '@/ui-components'
import { useEffect, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { useAppDispatch } from '@/store/hooks'
import { getTreasuryDetail } from '@/network/treasury'
import { get } from 'lodash'
import { setUserTreasury } from '@/store/treasurySlice'
import to from 'await-to-js'
import { dialog } from '@/utils'
import * as Image from './images'
import TreasuryMarket from '../market'
import TreasuryLottery from '../lottery'
import TreasuryHome from '../home'
import TreasuryTask from '../task'
import TreasuryUser from '../user'
import './index.scss'

const tabBar = {
  list: [
    {
      image: Image.market,
      selectedImage: Image.marketActive,
      pagePath: 'pages/treasury/market/index',
      title: '商城',
      page: () => <TreasuryMarket />
    },
    {
      image: Image.lottery,
      selectedImage: Image.lotteryActive,
      pagePath: 'pages/treasury/lottery/index',
      title: '抽奖',
      page: () => <TreasuryLottery />
    },
    {
      image: Image.home,
      selectedImage: Image.homeActive,
      pagePath: 'pages/treasury/home/index',
      title: '首页',
      page: () => <TreasuryHome />
    },
    {
      image: Image.task,
      selectedImage: Image.taskActive,
      pagePath: 'pages/treasury/task/index',
      title: '任务',
      page: () => <TreasuryTask />
    },
    {
      image: Image.user,
      selectedImage: Image.userActive,
      pagePath: 'pages/treasury/user/index',
      title: '个人',
      page: () => <TreasuryUser />
    }
  ]
}


export default function Treasury() {

  const [isComplete, setIsComplete] = useState(false)
  const [current, setCurrent] = useState(2)
  const dispatch = useAppDispatch()

  useDidShow(async () => {
    const userTreasuryId =  Number(get(Taro.getCurrentInstance().router, 'params.userTreasuryId', -1))

    if (userTreasuryId) {
      const [err, userTreasury] = await to(getTreasuryDetail(userTreasuryId, { hideLoading: !isComplete }))
      if (err) {
        Dialog.toast(err.message || '获取宝库信息失败, 请稍后重试')
        return
      }
      setIsComplete(true)
      dispatch(setUserTreasury(userTreasury))
    }
  })

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: tabBar.list[current].title
    })
  }, [current])

  return (
    <View className='treasury-index'>
      { tabBar.list[current].page() }
      <View className='bottom'></View>
      <Tabbar
        fixed
        current={current}
        tabList={tabBar.list}
        onClick={setCurrent}
        iconSize={30}
      />
    </View>
  )
}
